package com.xp.basic.heima.nio.netty.simpledemo.worker;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;


/***
 * 可以将 通道中的所有 handle 在 EmbedChannel 中实现 测试
 */
public class TestEmbededChannel {
    public static void main(String[] args) {
        ChannelInboundHandlerAdapter inboundHandlerAdapter1 = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                System.out.println(Thread.currentThread().getName() + " 1 ");
                super.channelRead(ctx, msg);
            }
        };

        ChannelInboundHandlerAdapter inboundHandlerAdapter2 = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                System.out.println(Thread.currentThread().getName() + " 2 ");
                super.channelRead(ctx, msg);
            }
        };

        ChannelOutboundHandlerAdapter outboundHandlerAdapter3 = new ChannelOutboundHandlerAdapter() {
            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                System.out.println(Thread.currentThread().getName() + " 3  ");
                super.write(ctx, msg, promise);
            }
        };

        ChannelOutboundHandlerAdapter outboundHandlerAdapter4 = new ChannelOutboundHandlerAdapter() {
            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                System.out.println(Thread.currentThread().getName() + " 4  ");
                super.write(ctx, msg, promise);
            }
        };

        EmbeddedChannel embeddedChannel = new EmbeddedChannel(inboundHandlerAdapter1, inboundHandlerAdapter2, outboundHandlerAdapter3, outboundHandlerAdapter4);
        //测试入站
//        embeddedChannel.writeInbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("hello".getBytes(StandardCharsets.UTF_8)));
        //测试出站
        embeddedChannel.writeOutbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("hello".getBytes(StandardCharsets.UTF_8)));
    }
}
